package db

import (
	"fmt"
	. "game_server/internal"
	. "game_server/logic/internal"
	_ "github.com/go-sql-driver/mysql"
	"os"
	"xorm.io/core"
	"xorm.io/xorm"
	"xorm.io/xorm/log"
)

var (
	PlayerMysql *xorm.Engine
)

func init() {
	Skeleton.AfterInit(func() {
		initMysql()
	})
}

func initMysql() (err error) {
	config := Config.Mysql
	if config.IP == "" {
		return
	}

	source := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8",
		config.User,
		config.Password,
		config.IP,
		config.Port,
		config.Database,
	)

	if PlayerMysql, err = xorm.NewEngine("mysql", source); err != nil {
		return
	}

	logger := log.NewSimpleLogger3(os.Stdout, "mysql", log.DEFAULT_LOG_FLAG, log.LOG_DEBUG)
	PlayerMysql.SetLogger(logger)
	if err = PlayerMysql.Ping(); err != nil {
		return
	}

	tableMapper := core.NewPrefixMapper(new(core.SnakeMapper), "player_")
	PlayerMysql.SetTableMapper(tableMapper)

	fieldMapper := new(core.SameMapper)
	PlayerMysql.SetColumnMapper(fieldMapper)

	//PlayerMysql.SetMaxIdleConns()
	//PlayerMysql.SetMaxOpenConns()

	return
}
